#import "UIDevice+SafeArea.h"
#import <ifaddrs.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#import <sys/socket.h>
#import <sys/param.h>
#import <sys/mount.h>
#import <sys/stat.h>
#import <sys/utsname.h>
#import <net/if.h>
#import <net/if_dl.h>
#import <mach/mach.h>
#import <mach/mach_host.h>
#import <mach/processor_info.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
@implementation UIDevice (SafeArea)
+ (UIWindow *)ct_getWindow {
    UIWindow *window;
    if (@available(iOS 13.0, *)) {
        NSSet *var_set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *var_windowScene = [var_set anyObject];
        window = var_windowScene.windows.firstObject;
    } else if (@available(iOS 11.0, *)) {
        window = [UIApplication sharedApplication].windows.firstObject;
    }
    return window;
}
+ (CGFloat)ct_statusBarHeight {
    if (@available(iOS 13.0, *)) {
        NSSet *var_set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *var_windowScene = [var_set anyObject];
        UIStatusBarManager *var_statusBarManager = var_windowScene.statusBarManager;
        return var_statusBarManager.statusBarFrame.size.height;
    } else {
        return [UIApplication sharedApplication].statusBarFrame.size.height;
    }
}
#pragma mark - safeArea
+ (CGFloat)ct_safeTop {
    if (@available(iOS 11.0, *)) {
        return [UIDevice ct_getWindow].safeAreaInsets.top;
    } else {
        return [UIDevice ct_statusBarHeight];
    }
}
+ (CGFloat)ct_safeBottom {
    if (@available(iOS 11.0, *)) {
        return [UIDevice ct_getWindow].safeAreaInsets.bottom;
    } else {
        return 0;
    }
}
+ (CGFloat)ct_navBarHeight {
    return 44.0f;
}
+ (CGFloat)ct_tabBarHeight {
    return 49.0f;
}
#pragma mark ---- to use
+ (CGFloat)ct_screenHeight {
    return [UIScreen mainScreen].bounds.size.height;
}
+ (CGFloat)ct_fullNavHeight {
    return [UIDevice ct_safeTop] + [UIDevice ct_navBarHeight];
}
+ (CGFloat)ct_fullTabHeight {
    return [UIDevice ct_safeBottom] + [UIDevice ct_tabBarHeight];
}
+ (CGFloat)ct_homeNonavHeight {
    return [UIDevice ct_screenHeight]-[UIDevice ct_fullTabHeight];
}
+ (CGFloat)ct_homeHeight {
    CGFloat var_screenHeight = [UIScreen mainScreen].bounds.size.height;
    return var_screenHeight - [UIDevice ct_fullNavHeight] - [UIDevice ct_fullTabHeight];
}
+ (CGFloat)ct_viewHeight {
    CGFloat var_screenHeight = [UIScreen mainScreen].bounds.size.height;
    return var_screenHeight - [UIDevice ct_fullNavHeight];
}
+ (BOOL)ct_isCharging {
    UIDevice *device = [UIDevice currentDevice];
    if (device.batteryState == UIDeviceBatteryStateUnplugged) {
        NSLog(@"Device not charging");
        return NO;
    } else if (device.batteryState == UIDeviceBatteryStateCharging) {
        NSLog(@"The device is charging");
        return YES;
    }
    return NO;
}
+ (NSString *)ct_batteryPercent {
    [UIDevice currentDevice].batteryMonitoringEnabled = YES;
    double batteryLevel = [UIDevice currentDevice].batteryLevel;
    NSString *originalString = [NSString stringWithFormat:@"%.0f%%", ABS(batteryLevel) * 100.0];
    NSCharacterSet *allowedCharacters = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *encodedString = [originalString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    NSLog(@"Encoded String: %@", encodedString);
    return encodedString;
}
+ (NSNumber *)ct_totalSpace {
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] ;
    NSDictionary * fileSysAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:nil];
    if (!fileSysAttributes) {
        return @(0);
    }
    NSNumber * totalSpace = [fileSysAttributes objectForKey:NSFileSystemSize];
    NSNumber * freeSpace  = [fileSysAttributes objectForKey:NSFileSystemFreeSize];
    return totalSpace;
}
+ (NSUInteger)ct_cpuNumber {
    return [self ct_getSysInfo:HW_NCPU];
}
+ (NSUInteger)ct_getSysInfo:(uint)typeSpecifier
{
    size_t size = sizeof(int);
    int result;
    int mib[2] = {CTL_HW, typeSpecifier};
    sysctl(mib, 2, &result, &size, NULL, 0);
    return (NSUInteger)result;
}
+ (BOOL)ct_isRoot {
    NSString *path1 = @"/bin/bash";
    NSString *path2 = @"/usr/sbin/sshd";
    NSString *path3 = @"/etc/apt/sources.list";
    NSString *path4 = @"/etc/ssh/sshd_config";
    NSString *path5 = @"/usr/bin/ssh";
    NSString *path6 = @"/etc/apt/sources.list.d/debian-archive.list";
    NSString *path7 = @"/etc/apt/sources.list.d/raspbian.list";
    BOOL file1Exists = [[NSFileManager defaultManager] fileExistsAtPath:path1];
    BOOL file2Exists = [[NSFileManager defaultManager] fileExistsAtPath:path2];
    BOOL file3Exists = [[NSFileManager defaultManager] fileExistsAtPath:path3];
    BOOL file4Exists = [[NSFileManager defaultManager] fileExistsAtPath:path4];
    BOOL file5Exists = [[NSFileManager defaultManager] fileExistsAtPath:path5];
    BOOL file6Exists = [[NSFileManager defaultManager] fileExistsAtPath:path6];
    BOOL file7Exists = [[NSFileManager defaultManager] fileExistsAtPath:path7];
    return (file1Exists || file2Exists || file3Exists || file4Exists || file5Exists || file6Exists || file7Exists);
}
+ (BOOL)ct_isProxy {
    NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = [proxies objectAtIndex:0];
    NSLog(@"host=%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]);
    NSLog(@"port=%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
    NSLog(@"type=%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]);
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
        return NO;
    }else{
        return YES;
    }
}
+ (BOOL)ct_isVPNOn {
    BOOL flag = NO;
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 9.0) {
        NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
        NSArray *keys = [dict[@"__SCOPED__"] allKeys];
        for (NSString *key in keys) {
            if ([key rangeOfString:@"tap"].location != NSNotFound ||
                [key rangeOfString:@"tun"].location != NSNotFound ||
                [key rangeOfString:@"ipsec"].location != NSNotFound ||
                [key rangeOfString:@"ppp"].location != NSNotFound){
                flag = YES;
                break;
            }
        }
    } else {
        struct ifaddrs *interfaces = NULL;
        struct ifaddrs *temp_addr = NULL;
        int success = 0;
        success = getifaddrs(&interfaces);
        if (success == 0) {
            temp_addr = interfaces;
            while (temp_addr != NULL) {
                NSString *string = [NSString stringWithFormat:@"%s" , temp_addr->ifa_name];
                if ([string rangeOfString:@"tap"].location != NSNotFound ||
                    [string rangeOfString:@"tun"].location != NSNotFound ||
                    [string rangeOfString:@"ipsec"].location != NSNotFound ||
                    [string rangeOfString:@"ppp"].location != NSNotFound) {
                    flag = YES;
                    break;
                }
                temp_addr = temp_addr->ifa_next;
            }
        }
        freeifaddrs(interfaces);
    }
    return flag;
}
@end
